﻿#pragma execution_character_set("utf-8")
#include "websocketwnd.h"
#include "ui_websocketwnd.h"

#include <boost/beast/core.hpp>
#include <boost/beast/websocket.hpp>
#include <boost/asio/connect.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <cstdlib>
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include "boost/filesystem.hpp"
//#include <boost/endian/endian.hpp>
#include <boost/endian/conversion.hpp>
using namespace std;

namespace beast = boost::beast;         // from <boost/beast.hpp>
namespace http = boost::beast::http;           // from <boost/beast/http.hpp>
namespace websocket = boost::beast::websocket; // from <boost/beast/websocket.hpp>
namespace net = boost::asio;            // from <boost/asio.hpp>
using tcp = boost::asio::ip::tcp;       // from <boost/asio/ip/tcp.hpp>


WebSocketWnd::WebSocketWnd(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::WebSocketWnd)
{
    ui->setupUi(this);
    //设置定时器关联
    connect(&timer_, &QTimer::timeout, this, &WebSocketWnd::startSendData);
    //停止计数器
    connect(ui->pushButton_stop, &QPushButton::clicked, [&]() {
        timer_.stop();
        });




    this->show();

    settings_ = new QSettings(QApplication::applicationDirPath() + "/NetworkConfig.ini", QSettings::IniFormat);
    settings_->setIniCodec("UTF8");

    ui->lineEdit_file->setText(settings_->value("src_path").toString());
    if(settings_->value("send_interval").isValid()){
        ui->spinBox_interval->setValue(settings_->value("send_interval").toInt());
    }
    QDir dir(ui->lineEdit_file->text());

    file_list_ = dir.entryList(QDir::Files,QDir::Name);

    async_process_ = new AsyncProcess();
    thread_ = new QThread(this);
    async_process_->moveToThread(thread_);

    // 选择路径
    connect(ui->pushButton_choose, &QPushButton::clicked,[=](){
        QString file_path = QFileDialog::getExistingDirectory(this,"", settings_->value("src_path").toString());
        ui->lineEdit_file->setText(file_path);

        QDir dir(file_path);

        //file_list_=dir.entryList(QDir::Files, QDir::Time| QDir::Reversed);
        file_list_ = dir.entryList(QDir::Files, QDir::Name);

        settings_->setValue("src_path", file_path);
    });

//    connect(thread_->thread(), SIGNAL(started()), async_process_, SLOT(startWebSocket()));
    connect(thread_->thread(), SIGNAL(finished()), async_process_, SLOT(deleteLater()));
//    connect(this, &WebSocketWnd::start_net, async_process_, &AsyncProcess::startWebSocket);
    //启动信号量
    connect(this, &WebSocketWnd::start_net, async_process_, &AsyncProcess::connectWebSocketServer);

    //循环发送按钮
    void(WebSocketWnd::*backSigna)(QString) = &WebSocketWnd::mySignal;
    connect(this, backSigna, async_process_, &AsyncProcess::sendData);
//    thread_->thread()->start();
    thread_->start();
    //连接服务器
    connect(ui->pushButton_connect, &QPushButton::clicked,[&](){
        async_process_->host = ui->lineEdit_ip->text().toStdString();
        async_process_->port = ui->spinBox_port->text().toStdString();
        emit start_net();
    });
}

WebSocketWnd::~WebSocketWnd()
{
    delete ui;
    delete settings_;
    async_process_->thread()->quit();
    async_process_->thread()->wait();
//    async_process_->thread()->exit();
}

void WebSocketWnd::on_pushButton_send_clicked()
{
    QString  path = "G:/20_data/raw/20210808/B4-Frame00007715.raw";
    //emit mySignal();
    //emit mySignal("G:/20_data/raw/20210808/B4-Frame00007715.raw");

    file_index_ = ui->spinBox_file_start->value();
    int interval = ui->spinBox_interval->value();
    cycle_times_ = ui->spinBox_cycle_times->value();
    timer_.start(interval);
    settings_->setValue("send_interval", interval);
}
void WebSocketWnd::startSendData()
{
    if (file_index_  >= file_list_.size()) {
        if (cycle_times_ == 1) {
            timer_.stop();
            return;
        }
        else {
            cycle_times_--;
            file_index_ = ui->spinBox_file_start->value();
        }
    }
    QString file_path = ui->lineEdit_file->text() + "/" + file_list_[file_index_];
    ui->textBrowser->append(file_path);
    async_process_->sendData(file_path);
    ++file_index_;
    cv::Mat img;
    async_process_->getRecvData(img);
    img = img / 64;
    cv::Mat tt;
    std::vector<cv::Mat> oimg;
    cv::Mat _img;
    img.convertTo(tt, CV_8UC3);
    oimg.push_back(tt);
    oimg.push_back(tt.clone());
    oimg.push_back(tt.clone());
    cv::merge(oimg, _img);
    emit outDisplay(
        QPixmap::fromImage(
            QImage(
                _img.data,
                _img.cols,
                _img.rows,
                _img.step,
                QImage::Format_RGB888)
            .rgbSwapped()));

}

void WebSocketWnd::closeEvent(QCloseEvent* e)
{
    e->accept();
//    e->ignore();
}
